package com.gitee.aurora.server.dao.impl;

import com.gitee.aurora.comm.Constant;
import com.gitee.aurora.core.comm.AuroraJdbcTemplate;
import com.gitee.aurora.core.utils.ResultVO;
import com.gitee.aurora.core.utils.ResultVOUtils;
import com.gitee.aurora.server.dao.RuleConfigDao;
import com.gitee.aurora.server.vo.RuleVo;
import com.gitee.aurora.utils.PageParam;
import com.gitee.aurora.utils.Pagination;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import javax.annotation.Resource;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

@Repository
public class RuleConfigDaoImpl implements RuleConfigDao {

    @Value("${http.ssjzxgetDBTableField}")
    private String ssjzxgetDBTableField;

    @Value("${http.sjzxgetDBTableField}")
    private String sjzxgetDBTableField;

    @Autowired
    private AuroraJdbcTemplate auroraJdbcTemplate;

    @Resource
    private RestTemplate restTemplate;

    @Override
    public Pagination queryRule(RuleVo ruleVo, PageParam pageParam) {
        List<Object> params = new ArrayList<>();
        StringBuilder sql = new StringBuilder("SELECT T1.ID AS id, T1.TABLE_NAME AS tableName, T1.RULE AS rule, T1.DEPT_CODE AS deptCode, T2.PT_IP AS sjzxIp FROM TAB_RULE T1 INNER JOIN TAB_PTCJ_CONFIG T2 ON T1.DEPT_CODE = T2.S_CODE WHERE 1 =1");
        if (ruleVo != null){
            if (ruleVo.getDeptCode() != null && !"".equals(ruleVo.getDeptCode())){
                sql.append(" and T1.DEPT_CODE = ?");
                params.add(ruleVo.getDeptCode());
            }
            if (ruleVo.getTableName() != null && !"".equals(ruleVo.getTableName())){
                sql.append(" and T1.TABLE_NAME = ?");
                params.add(ruleVo.getTableName());
            }
        }
        return new Pagination(sql.toString(),params.toArray(),pageParam,auroraJdbcTemplate);
    }


    public List<RuleVo> queryRule(RuleVo ruleVo) {
        List<Object> params = new ArrayList<>();
        StringBuilder sql = new StringBuilder("SELECT ID AS id, TABLE_NAME AS tableName, RULE AS rule, DEPT_CODE AS deptCode FROM TAB_RULE WHERE 1=1");
        if (ruleVo != null){
            if (ruleVo.getDeptCode() != null){
                sql.append(" and DEPT_CODE = ?");
                params.add(ruleVo.getDeptCode());
            }
            if (ruleVo.getTableName() != null){
                sql.append(" and TABLE_NAME = ?");
                params.add(ruleVo.getTableName());
            }
        }
        return auroraJdbcTemplate.query(sql.toString(),new BeanPropertyRowMapper<>(RuleVo.class),params.toArray());
    }

    @Override
    public ResultVO updataRule(RuleVo ruleVo) {
        List<Object> params = new ArrayList<>();
        String sql = "UPDATE TAB_RULE SET RULE = ? WHERE 1 = 1 AND DEPT_CODE = ? and TABLE_NAME = ?";
        if (ruleVo == null || ruleVo.getTableName() == null || "".equals(ruleVo.getTableName()) || ruleVo.getDeptCode() == null || "".equals(ruleVo.getDeptCode())){
            return ResultVOUtils.error("请求参数有误");
        }
        if (ruleVo.getRule() == null || "".equals(ruleVo.getRule())){
            return ResultVOUtils.error("规则不能为空");
        }
        params.add(ruleVo.getRule());
        params.add(ruleVo.getDeptCode());
        params.add(ruleVo.getTableName());
        int res = auroraJdbcTemplate.update(sql, params.toArray());
        if (res!=1){
            return ResultVOUtils.error("数据库操作异常");
        }
        return ResultVOUtils.success("更行成功！");
    }

    @Override
    public ResultVO addRule(RuleVo ruleVo) {
        List<RuleVo> ruleVos = queryRule(ruleVo);
        if (ruleVos.size()>0){
            return ResultVOUtils.error("该记录已存在允许再次添加，请进行更新操作");
        }
        String sql = "INSERT INTO TAB_RULE(TABLE_NAME, RULE, DEPT_CODE) VALUES (?,?,?)";
        int res = auroraJdbcTemplate.update(sql, new String[]{ruleVo.getTableName(), ruleVo.getRule(), ruleVo.getDeptCode()});
        if (res != 1){
            return ResultVOUtils.error("添加失败，系统异常");
        }
        return ResultVOUtils.success("添加成功");
    }

    @Override
    @Transactional
    public ResultVO deleteRule(List<RuleVo> ruleVoList) {
        String idList = "";
        if (ruleVoList == null && ruleVoList.size()==0){
            return ResultVOUtils.error("上传参数有误");
        }
        for (RuleVo ruleVo:ruleVoList) {
            idList=idList+ruleVo.getId()+",";
        }
        String sql = "DELETE FROM TAB_RULE where 1=1 AND ID IN ("+idList.replaceFirst(".$", "")+")";
        int res = auroraJdbcTemplate.update(sql);
        if (res != 1){
            return ResultVOUtils.error("数据库操作异常");
        }
        return ResultVOUtils.success("删除成功");
    }

    @Override
    public ResultVO getDBTableField(RuleVo ruleVo) {
        if(ruleVo==null || ruleVo.getTableName() == null || "".equals(ruleVo.getTableName()) || ruleVo.getSjzxIp() == null || "".equals(ruleVo.getSjzxIp())){
            return ResultVOUtils.error("参数错误，接口调用失败");
        }
        String substring = ruleVo.getSjzxIp().substring(ruleVo.getSjzxIp().substring(0, ruleVo.getSjzxIp().indexOf(":")).length() + 1, ruleVo.getSjzxIp().length());
        String requestUrl = "";
        if ("10000".equals(substring)){
            requestUrl =ssjzxgetDBTableField.replace(Constant.ip,ruleVo.getSjzxIp());
        }else{
            requestUrl =sjzxgetDBTableField.replace(Constant.ip,ruleVo.getSjzxIp());
        }
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<String> httpEntity = new HttpEntity<>(ruleVo.getTableName(),headers);
        URI url = UriComponentsBuilder.fromUriString(requestUrl).build().toUri();
        ResponseEntity<ResultVO> responseSjzx = restTemplate.postForEntity(url,httpEntity,ResultVO.class);
        return responseSjzx.getBody();
    }

    @Override
    public List<String> getCheckTableList() {
        String sql = "SELECT PT_TABLE FROM TAB_PT_CONFIG GROUP BY PT_TABLE";
        List<String> tableList = auroraJdbcTemplate.queryForList(sql, String.class);
        return tableList;
    }
}
